<template>
  <div class="app-container calendar-list-container">

    <el-card class="box-card">
      <h3>服务项目介绍</h3>
      <el-form :rules="rules" ref="goods" :model="goods" label-width="150px">
        <el-form-item label="服务项目编号" prop="goodsSn">
          <el-input v-model="goods.goodsSn" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="服务项目名称" prop="name">
          <el-input v-model="goods.name"></el-input>
        </el-form-item>

        <el-form-item label="专柜价格" prop="counterPrice">
          <el-input-number v-model="goods.counterPrice" :min="1">
          </el-input-number>
        </el-form-item>

        <el-form-item label="积分价格" prop="retailPrice">
          <el-input-number v-model="goods.retailPrice" :min="1">
          </el-input-number>
        </el-form-item>

        <el-form-item label="限购数量" prop="limitNumber">
          <el-input-number v-model="goods.limitNumber" :min="1">
          </el-input-number>
        </el-form-item>

        <el-form-item label="是否新品" prop="isNew">
          <el-radio-group v-model="goods.isNew">
            <el-radio :label="true">新品</el-radio>
            <el-radio :label="false">非新品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否在售" prop="isOnSale">
          <el-radio-group v-model="goods.isOnSale">
            <el-radio :label="true">在售</el-radio>
            <el-radio :label="false">未售</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="goods.isOnSale" label="有效期开始时间" prop="discountsAddTime">
          <el-date-picker class="filter-item" v-model="goods.discountsAddTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions0" align="right">
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="goods.isOnSale" label="有效期结束时间" prop="discountsEndTime">
          <el-date-picker class="filter-item" v-model="goods.discountsEndTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions1" align="right">
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="goods.isOnSale" label="购买开始时间" prop="buyAddTime">
          <el-date-picker class="filter-item" v-model="goods.buyAddTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions2" align="right">
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="goods.isOnSale" label="购买结束时间" prop="buyEndTime">
          <el-date-picker class="filter-item" v-model="goods.buyEndTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions3" align="right">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="服务项目图片">
          <el-upload class="avatar-uploader" :headers="headers" :action='uploadPath' list-type="picture-card" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif" :on-success="uploadPicUrl">
            <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item label="宣传画廊">
          <el-upload :action='uploadPath' :headers="headers" :limit='5' multiple accept=".jpg,.jpeg,.png,.gif" :file-list="galleryFileList" list-type="picture-card" :on-exceed='uploadOverrun' :on-success="handleGalleryUrl" :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item> -->

        <el-form-item label="服务项目单位">
          <el-input v-model="goods.unit"></el-input>
        </el-form-item>

        <el-form-item label="关键字">
          <el-tag :key="tag" v-for="tag in keywords" closable type="primary" @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-keyword" v-if="newKeywordVisible" v-model="newKeyword" ref="newKeywordInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-keyword" size="small" type="primary" @click="showInput">+ 增加</el-button>
        </el-form-item>

        <!-- <el-form-item label="服务项目简介">
          <el-input v-model="goods.brief"></el-input>
        </el-form-item> -->

        <el-form-item label="服务项目详细介绍">
          <textarea :init="editorInit" v-model="goods.desc" style="width:100%" rows='6' maxlength='-1' auto-height='true'></textarea>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>服务项目库存</h3>
      <el-table :data="products">
        <el-table-column property="value" label="服务项目规格">
          <template slot-scope="scope">
            <el-tag :key="tag" v-for="tag in scope.row.specifications">
              {{tag}}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column property="price" width="150" label="服务项目售价(积分)">
        </el-table-column>

        <el-table-column property="number" width="150" label="服务项目数量">
        </el-table-column>

        <el-table-column property="url" width="150" label="服务项目图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="40" v-if="scope.row.url" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleProductShow(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="设置服务项目" :visible.sync="productVisiable">
        <el-form :rules="rules" ref="productForm" :model="productForm" status-icon label-position="left" label-width="130px" style='width: 400px; margin-left:50px;'>
          <el-form-item label="服务项目规格列" prop="specifications">
            <el-tag :key="tag" v-for="tag in productForm.specifications">
              {{tag}}
            </el-tag>
          </el-form-item>

          <el-form-item label="服务项目售价(积分)" prop="price">
            <el-input-number v-model="productForm.price" :min="1"></el-input-number>
          </el-form-item>

          <el-form-item label="服务项目数量" prop="number">
            <el-input v-model="productForm.number"></el-input>
          </el-form-item>

          <el-form-item label="服务项目图片" prop="url">
            <el-upload class="avatar-uploader" :headers="headers" :action='uploadPath' list-type="picture-card" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif" :on-success="uploadProductUrl">
              <img v-if="productForm.url" :src="productForm.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="productVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleProductEdit">确定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <el-card class="box-card">
      <h3>服务项目参数</h3>
      <el-button :plain="true" @click="handleAttributeShow" type="primary">添加</el-button>
      <el-table :data="attributes">
        <el-table-column property="attribute" label="服务项目参数名称">
        </el-table-column>

        <el-table-column property="value" label="服务项目参数值">
        </el-table-column>

        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleAttributeDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="设置服务项目参数" :visible.sync="attributeVisiable">
        <el-form ref="attributeForm" :model="attributeForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
          <el-form-item label="服务项目参数名称" prop="attribute">
            <el-input v-model="attributeForm.attribute"></el-input>
          </el-form-item>

          <el-form-item label="服务项目参数值" prop="value">
            <el-input v-model="attributeForm.value"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="attributeVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button @click="handleEdit" :disabled="isDisable" type="primary">更新服务项目</el-button>
    </div>

  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { detailGoods, editGoods } from '@/api/goodsManage'
import { createStorage, uploadPath } from '@/api/storage'
import store from '@/store'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'GoodsEdit',
  components: { Editor },
  computed: {
    headers() {
      return {
        'X-Token': getToken()
      }
    }
  },
  data() {
    return {
      uploadPath,
      newKeywordVisible: false,
      newKeyword: '',
      keywords: [],
      galleryFileList: [],
      goods: { gallery: [] },
      specVisiable: false,
      specForm: { specification: '', value: '', picUrl: '' },
      specifications: [{ specification: '规格', value: '标准', picUrl: '' }],
      productVisiable: false,
      categoryId: 0,
      productForm: {
        id: 0,
        specifications: [],
        price: 0.0,
        number: 1,
        url: ''
      },
      products: [
        {
          id: 0,
          specifications: ['标准'],
          price: 0.0,
          number: 0,
          url: ''
        }
      ],
      listQuery_1: {
        mechanismId: store.getters.mechanismId
      },
      attributeVisiable: false,
      attributeForm: { attribute: '', value: '' },
      attributes: [],
      isDisable: false,
      rules: {
        goodsSn: [{ required: true, message: '服务项目编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '服务项目名称不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autoresize autosave emoticons fullscreen hr   importcss insertdatetime legacyoutput link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript ',
          'hr bullist numlist link  charmap preview anchor pagebreak fullscreen media table emoticons forecolor backcolor'
        ],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData)
            .then(res => {
              success(res.data.data.url)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      },
      pickerOptions0: this.beginDate(),
      pickerOptions1: this.processDate(),
      pickerOptions2: this.beginBuyDate(),
      pickerOptions3: this.processBuyDate()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      if (this.$route.query.id == null) {
        return
      }

      const goodsId = this.$route.query.id
      detailGoods(goodsId).then(response => {
        this.goods = response.data.data.goods
        if (this.goods.limitNumber === undefined) {
          this.goods.limitNumber = 1
        }
        this.specifications = response.data.data.specifications
        this.products = response.data.data.products
        this.attributes = response.data.data.attributes
        if (this.goods.keywords !== '') {
          this.keywords = this.goods.keywords.split(',')
        }
        // this.keywords.push(this.goods.keywords)
        this.galleryFileList = []
        for (var i = 0; i < this.goods.gallery.length; i++) {
          this.galleryFileList.push({
            url: this.goods.gallery[i]
          })
        }
      })
    },
    beginDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.goods.discountsEndTime) {
            return new Date(self.goods.discountsEndTime).getTime() < time.getTime() || time.getTime() < Date.now() - 8.64e7
          } else {
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },
    processDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.goods.discountsAddTime) {
            return new Date(self.goods.discountsAddTime).getTime() > time.getTime() + 8.54e7 || time.getTime() < Date.now() - 8.64e7
          } else {
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },
    beginBuyDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.goods.buyEndTime) {
            return new Date(self.goods.buyEndTime).getTime() < time.getTime() || time.getTime() < Date.now() - 8.64e7
          } else {
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },
    processBuyDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.goods.buyAddTime) {
            return new Date(self.goods.buyAddTime).getTime() > time.getTime() + 8.54e7 || time.getTime() < Date.now() - 8.64e7
          } else {
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },
    handleCancel: function() {
      this.$router.push({ path: '/goodsManage/list' })
    },
    handleEdit: function() {
      if (this.goods.name == null || this.goods.name === '') {
        this.$message({
          message: '服务项目名称不能为空',
          type: 'warning'
        })
        return false
      }
      if (this.goods.desc == null || this.goods.desc === '') {
        this.$message({
          message: '服务项目详细介绍不能为空',
          type: 'warning'
        })
        return false
      }
      if (this.goods.picUrl == null || this.goods.picUrl === '') {
        this.$message({
          message: '服务项目图片不能为空',
          type: 'warning'
        })
        return false
      }
      if (this.goods.retailPrice <= 0) {
        this.$message({
          message: '积分价格必须大于0',
          type: 'warning'
        })
        return false
      }
      if (this.goods.limitNumber <= 0) {
        this.$message({
          message: '限购数量必须大于0',
          type: 'warning'
        })
        return false
      }
      if (this.goods.isOnSale === true) {
        if (this.goods.discountsAddTime == null || this.goods.discountsAddTime === '') {
          this.$message({
            message: '有效期开始时间不能为空',
            type: 'warning'
          })
          return false
        }
        if (this.goods.discountsEndTime == null || this.goods.discountsEndTime === '') {
          this.$message({
            message: '有效期结束时间不能为空',
            type: 'warning'
          })
          return false
        }
        if (this.goods.buyAddTime == null || this.goods.buyAddTime === '') {
          this.$message({
            message: '购买开始时间不能为空',
            type: 'warning'
          })
          return false
        }
        if (this.goods.buyEndTime == null || this.goods.buyEndTime === '') {
          this.$message({
            message: '购买结束时间不能为空',
            type: 'warning'
          })
          return false
        }
      }
      if (this.productForm.number < 0) {
        this.$message({
          message: '服务项目数量必须大于0',
          type: 'warning',
          duration: 5000
        })
        return false
      }
      if ((this.goods.retailPrice !== this.productForm.price) && this.productForm.price !== 0) {
        this.$message({
          message: '积分价格必须和规格中的服务项目售价相同',
          type: 'warning',
          duration: 5000
        })
        return false
      }
      this.$confirm('更新之后需要重新提交审核，是否更新?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.isDisable = true
          const loading = this.$loading({
            lock: true,
            text: '更新中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // this.goods.desc = this.goods.desc.replace('<p>', '').replace('</p>', '')
          const finalGoods = {
            mechanismGoods: this.goods,
            mechanismSpecifications: this.specifications,
            mechanismProducts: this.products,
            mechanismAttributes: this.attributes
          }
          editGoods(finalGoods)
            .then(response => {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 5000
              })
              loading.close()
              this.isDisable = false
              this.$router.push({ path: '/goodsManage/list' })
            })
            .catch(response => {
              MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        })
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
      this.goods.keywords = this.keywords.toString()
    },
    showInput() {
      this.newKeywordVisible = true
      this.$nextTick(_ => {
        this.$refs.newKeywordInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword
      if (newKeyword) {
        this.keywords.push(newKeyword)
        this.goods.keywords = this.keywords.toString()
      }
      this.newKeywordVisible = false
      this.newKeyword = ''
    },
    uploadPicUrl: function(response) {
      this.goods.picUrl = response.data.url
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url)
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1)
        }
      }
    },
    specChanged: function(label) {
      if (label === false) {
        this.specifications = [{ specification: '规格', value: '标准', picUrl: '' }]
        this.products = [{ id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }]
      } else {
        this.specifications = []
        this.products = []
      }
    },
    specToProduct() {
      if (this.specifications.length === 0) {
        return
      }
      // 根据specifications创建临时规格列表
      var specValues = []
      var spec = this.specifications[0].specification
      var values = []
      values.push(0)

      for (var i = 1; i < this.specifications.length; i++) {
        const aspec = this.specifications[i].specification

        if (aspec === spec) {
          values.push(i)
        } else {
          specValues.push(values)
          spec = aspec
          values = []
          values.push(i)
        }
      }
      specValues.push(values)

      // 根据临时规格列表生产服务项目规格
      // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
      var productsIndex = 0
      var products = []
      var combination = []
      var n = specValues.length
      for (var s = 0; s < n; s++) {
        combination[s] = 0
      }
      var index = 0
      var isContinue = false
      do {
        var specifications = []
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]]
          specifications.push(this.specifications[z].value)
        }
        products[productsIndex] = { id: productsIndex, specifications: specifications, price: 0.0, number: 0, url: '' }
        productsIndex++

        index++
        combination[n - 1] = index
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0
            index = 0
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1
            }
          }
        }
        isContinue = false
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true
          }
        }
      } while (isContinue)

      this.products = products
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row)
      this.productVisiable = true
    },
    uploadProductUrl: function(response) {
      this.productForm.url = response.data.url
    },
    handleProductEdit() {
      this.$refs['productForm'].validate(valid => {
        if (valid) {
          for (var i = 0; i < this.products.length; i++) {
            const v = this.products[i]
            if (v.id === this.productForm.id) {
              this.products.splice(i, 1, this.productForm)
              break
            }
          }
          this.productVisiable = false
        }
      })
    },
    handleAttributeShow() {
      this.attributeForm = {}
      this.attributeVisiable = true
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm)
      this.attributeVisiable = false
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row)
      this.attributes.splice(index, 1)
    },
    changeMin(value) {
      var _this = this
      var reg = /^[1-9]\d*$/
      if (!reg.test(value)) {
        _this.$alert('请输入正整数', '提醒', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
          }
        })
      }
    },
    changeAdd(value) {
      var _this = this
      var reg = /^[1-9]\d*$/
      if (!reg.test(value)) {
        _this.$alert('请输入正整数', '提醒', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
          }
        })
      }
    }
  }
}
</script>
